package my.action;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import my.jdbc.DbConUtil;
import my.jdbc.JdbcTemplate;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import util.BuildMenuUtil;
import bean.EasyUiTreeBean;
import bean.MenuBean;

@Controller
@RequestMapping("main")
public class MainIndexAction {

	@RequestMapping("toIndex")
	public ModelAndView toIndex(String title) {
		if (title.endsWith(".do")) {
			return new ModelAndView("redirect:/" + title);
		}
		return new ModelAndView(title);
	}

	@RequestMapping("toTest")
	public ModelAndView toTest() {
		return new ModelAndView("bootcss_1");
	}

	@RequestMapping("login")
	public ModelAndView loginIndex(String username, String password, HttpSession session) {
		String sql = " SELECT password FROM user_info WHERE name = '" + username + "' ";
		Object[] passwordInfo = JdbcTemplate.queryFieldInfoByFields(DbConUtil.get162testCon(), sql, null, DbConUtil.TYPE_NAME_162TEST);

		if (passwordInfo == null || !passwordInfo[0].equals(password)) {
			return new ModelAndView("redirect:/login.jsp");
		}
		session.setAttribute("user", username);
		session.setAttribute("menuMap", JSONObject.fromObject(getMenuInfo()));
		return new ModelAndView("redirect:/");
	}

	public Object getMenuInfo() {
		String sql = " SELECT * FROM menu ORDER BY orderNo ";
		List<MenuBean> menuList = JdbcTemplate.queryListInfoByBean(DbConUtil.get162testCon(), sql, MenuBean.class, null, DbConUtil.TYPE_NAME_162TEST);
		Map<String, List<EasyUiTreeBean>> treeMap = BuildMenuUtil.buildIndexLeftMenu(menuList);
		return treeMap;
	}

}
